package com.hayukleung.voiceclient;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.hayukleung.base.BaseActivity;
import com.hayukleung.task.GetData;
import com.hayukleung.task.StartNetTask;
import com.hayukleung.task.UICallback;
import com.hayukleung.util.Constants;
import com.hayukleung.util.LogMgr;
import com.hayukleung.util.Util;

import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends BaseActivity
{
  private final static String TAG = "MainActivity";
  private EditText editUsername;
  private EditText editPassword;
  private Button btnLogin;
  private Button btnExit;
  public static String username;
  
  // label
  private final String LABEL_LOGIN_SUCCESS = "login_success";
  private final String LABEL_LOGIN_FAIL = "login_fail";
  private final String LABEL_UNKNOWN_ERROR = "unknown_error";
  private final String LABEL_NETWORK_ERROR = "network_error";

  /*
   * override methods =========================================================
   */
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    LogMgr.writeLog(TAG, "onCreate()", LogMgr.INFO);
    super.onCreate(savedInstanceState);
    environmentCheck();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public void setContentView()
  {
    super.setContentView();
    setContentView(R.layout.activity_main);
  }

  @Override
  public void initWidgets()
  {
    super.initWidgets();
    editUsername = (EditText) findViewById(R.id.main$editUsername);
    editPassword = (EditText) findViewById(R.id.main$editPassword);
    btnLogin = (Button) findViewById(R.id.main$btnLogin);
    btnExit = (Button) findViewById(R.id.main$btnExit);

    btnLogin.setOnClickListener(new ListenerLogin());
    btnExit.setOnClickListener(new ListenerExit());
  }

  /*
   * private methods ==========================================================
   */
  private String connect(String message) throws Exception
  {
    Socket socket = new Socket(Constants.SERVER_IPV4, Constants.SERVER_TCP_PORT_INT);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    out.write(message.getBytes());
    out.flush();
    byte[] reply = new byte[1024];
    in.read(reply);
    /*
     * about [AsyncTask-Looper-Toast] see
     * http://jeff-pluto-1874.iteye.com/blog/869710
     */
    if (new String(reply).trim().equalsIgnoreCase(Constants.REPLY_OK))
    { // login success
      socket.close();
      return LABEL_LOGIN_SUCCESS;
    }
    else if (new String(reply).trim().equalsIgnoreCase(Constants.REPLY_ERROR))
    {
      socket.close();
      return LABEL_LOGIN_FAIL;
    }
    else
    {
      socket.close();
      return LABEL_UNKNOWN_ERROR;
    }
  }

  private void environmentCheck()
  {
    if (!Util.hasSDCard())
    {
      Util.showToast(this, getString(R.string.no_sdcard));
      System.exit(0);
    }
  }

  /*
   * private class ============================================================
   */
  private class ListenerLogin implements OnClickListener
  {
    @Override
    public void onClick(View v)
    {
      username = editUsername.getText().toString();
      String password = editPassword.getText().toString();
      /*
       * login token: [login,username,password]
       */
      String message = Constants.REQ_LOGIN + Constants.COMMA + username + Constants.COMMA + password;
      /*
       * network operation in UI thread will cause
       * android.os.NetworkOnMainThreadException in version 4.0 or later use
       * AsyncTask instead
       */
      StartNetTask startNetTask = new StartNetTask(MainActivity.this, 
          new GetData() // do in doInBackground
          {
            String result;
            @Override
            public String getData(String... strings)
            {
              try
              {
                result = connect(strings[0]);
              }
              catch (Exception e)
              {
                e.printStackTrace();
                result = LABEL_NETWORK_ERROR;
              }
              return result;
            }
          }, 
          new UICallback() // do in onPostExecute
          {
            @Override
            public void callback(String responseString)
            {
              if (LABEL_LOGIN_SUCCESS.equals(responseString))
              {
                Util.showToast(MainActivity.this, getString(R.string.login_success));
                Intent intent = new Intent(MainActivity.this, MessageActivity.class);
                startActivity(intent);
                finish();
              }
              else if (LABEL_LOGIN_FAIL.equals(responseString))
              {
                Util.showToast(MainActivity.this, getString(R.string.login_fail));
              }
              else if (LABEL_UNKNOWN_ERROR.equals(responseString))
              {
                Util.showToast(MainActivity.this, getString(R.string.unknown_error));
              }
              else if (LABEL_NETWORK_ERROR.equals(responseString))
              {
                Util.showToast(MainActivity.this, getString(R.string.network_error));
              }
            }
          });
      startNetTask.requestData(message, true, true);
    }
  }

  private class ListenerExit implements OnClickListener
  {
    @Override
    public void onClick(View v)
    {
      System.exit(0);
    }
  }
}
